package com.sjw.smarturl.controller;

import com.sjw.smarturl.entity.vo.ResultMode;
import com.sjw.smarturl.entity.vo.UrlModel;
import com.sjw.smarturl.enums.StatusEnum;
import com.sjw.smarturl.service.ISmartUrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

/**
 * @author sjw
 * @className SmartUrlController
 * @date 2020/9/1 13:06
 * @description: 短链接服务：短链接生成、重定向
 */
@Controller
//@ResultAdvice
public class SmartUrlController {
    @Autowired
    private ISmartUrlService smartUrlService;

    /**
     * 编码
     *
     * @param urlModel 原始链接实体
     * @return 短链接
     */
    @ResponseBody
    @PostMapping("/smartUrl")
    public ResultMode smartUrl(@RequestBody UrlModel urlModel) {
        if (urlModel == null || StringUtils.isEmpty(urlModel.getUrl()))
            return ResultMode.errorInstance(StatusEnum.ILLEGAL_PARAMETER);
        String smartUrl = smartUrlService.encode(urlModel.getUrl());
        return ResultMode.okInstance(smartUrl);
    }

    /**
     * 解码重定向
     *
     * @param url 原始链接的编码
     * @return 重定向
     */
    @GetMapping("/r/{url}")
    public ModelAndView redirect(@PathVariable String url) {
        String originUrl = smartUrlService.decode(url);
        // TODO
        // 异常处理
        RedirectView redirectView = new RedirectView(originUrl);
        // 301永久重定向，避免网络劫持
        redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        return new ModelAndView(redirectView);
    }
}
